<template>
  <div class="appointment-list-container">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover">
        <div class="search-form">
          <!-- 医院名称搜索 -->
          <div class="search-item">
            <label>医院名称</label>
            <el-input 
              v-model="searchForm.hospitalName" 
              placeholder="请输入医院名称" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="search-buttons">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </div>
        </div>

        <!-- 状态筛选按钮 -->
        <div class="filter-section">
          <div class="filter-group">
            <label>预约状态：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.status === '' }"
                @click="filterByStatus('')">
                全部
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.status === '待赴约' }"
                @click="filterByStatus('待赴约')">
                待赴约
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.status === '已到店' }"
                @click="filterByStatus('已到店')">
                已到店
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.status === '已完成' }"
                @click="filterByStatus('已完成')">
                已完成
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 预约列表 -->
    <div class="appointment-list">
      <el-card 
        v-for="appointment in appointmentList" 
        :key="appointment.id"
        shadow="hover"
        class="appointment-card">
        <div class="appointment-header">
          <div class="appointment-title">
            <h3>{{ appointment.hospitalName }}</h3>
            <el-tag 
              :type="getStatusType(appointment.status)"
              size="medium">
              {{ appointment.status }}
            </el-tag>
          </div>
          <div class="appointment-time">
            预约时间：{{ formatDate(appointment.appointmentDate) }} {{ appointment.appointmentTime }}
          </div>
        </div>

        <div class="appointment-content">
          <div class="content-item">
            <label>宠物信息：</label>
            <span>{{ appointment.petName }}（{{ appointment.petType }}）</span>
          </div>
          <div class="content-item">
            <label>病情描述：</label>
            <span>{{ appointment.conditionDescription }}</span>
          </div>
          <div class="content-item" v-if="appointment.images">
            <label>病情图片：</label>
            <div class="image-list">
              <el-image 
                v-for="(image, index) in getImageList(appointment.images)" 
                :key="index"
                :src="image"
                :preview-src-list="getImageList(appointment.images)"
                fit="cover">
              </el-image>
            </div>
          </div>
          <div class="content-item">
            <label>联系电话：</label>
            <span>{{ appointment.contactPhone }}</span>
          </div>
          <div class="content-item">
            <label>创建时间：</label>
            <span>{{ formatDateTime(appointment.createTime) }}</span>
          </div>
        </div>

        <div class="appointment-actions" v-if="appointment.status === '待赴约'">
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-check"
            @click="reportArrival(appointment)">
            上报到店
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            icon="el-icon-close"
            @click="cancelAppointment(appointment)">
            取消预约
          </el-button>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty v-if="appointmentList.length === 0" description="暂无预约记录"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <el-pagination
        background
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getAppointmentList, cancelAppointment, updateAppointmentStatus } from '@/api/appointment';

export default {
  name: 'UserAppointmentList',
  data() {
    return {
      searchForm: {
        hospitalName: '',
        status: ''
      },
      appointmentList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    };
  },
  created() {
    this.loadAppointments();
  },
  methods: {
    // 加载预约列表
    async loadAppointments() {
      this.loading = true;
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (!userInfo) {
          this.$notify({
            title: '提示',
            message: '请先登录',
            type: 'warning',
            duration: 2000
          });
          this.$router.push('/login');
          return;
        }
        
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          userId: userInfo.id
        };
        
        if (this.searchForm.hospitalName) {
          params.hospitalName = this.searchForm.hospitalName;
        }
        if (this.searchForm.status) {
          params.status = this.searchForm.status;
        }
        
        const response = await getAppointmentList(params);
        if (response.data.success) {
          this.appointmentList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载预约记录失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载预约记录失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadAppointments();
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        hospitalName: '',
        status: ''
      };
      this.handleSearch();
    },
    
    // 按状态筛选
    filterByStatus(status) {
      this.searchForm.status = status;
      this.handleSearch();
    },
    
    // 翻页
    handlePageChange(page) {
      this.currentPage = page;
      this.loadAppointments();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    
    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        '待赴约': 'warning',
        '已到店': 'primary',
        '已完成': 'success'
      };
      return typeMap[status] || 'info';
    },
    
    // 获取图片列表
    getImageList(images) {
      if (!images) {
        return [];
      }
      return images.split(',');
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return '';
      const d = new Date(datetime);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 上报到店
    reportArrival(appointment) {
      this.$confirm('确认已到店吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        try {
          const response = await updateAppointmentStatus(appointment.id, '已到店');
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '上报到店成功',
              type: 'success',
              duration: 2000
            });
            this.loadAppointments();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '上报到店失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '上报到店失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    },
    
    // 取消预约
    cancelAppointment(appointment) {
      this.$confirm('确定要取消这个预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await cancelAppointment(appointment.id);
          if (response.data.success) {
            this.$notify({
              title: '成功',
              message: '已取消预约',
              type: 'success',
              duration: 2000
            });
            this.loadAppointments();
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message || '取消预约失败',
              type: 'error',
              duration: 2000
            });
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '取消预约失败，请稍后重试',
            type: 'error',
            duration: 2000
          });
        }
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.appointment-list-container {
  min-height: calc(100vh - 130px);
  padding-bottom: 20px;
}

/* 搜索筛选区域 */
.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.search-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.search-item .el-input {
  width: 200px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

/* 筛选按钮区域 */
.filter-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-group > label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  min-width: 90px;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-btn {
  padding: 8px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.filter-btn:hover {
  color: #2c5f2d;
  border-color: #2c5f2d;
  background: #f0f9f0;
}

.filter-btn.active {
  color: white;
  background: linear-gradient(135deg, #2c5f2d 0%, #97bc62 100%);
  border-color: #2c5f2d;
  font-weight: 600;
}

/* 预约列表 */
.appointment-list {
  min-height: 400px;
}

.appointment-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.appointment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.appointment-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.appointment-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.appointment-title h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2c5f2d;
  margin: 0;
}

.appointment-time {
  font-size: 14px;
  color: #909399;
}

.appointment-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.content-item {
  display: flex;
  font-size: 14px;
}

.content-item label {
  color: #909399;
  min-width: 80px;
  font-weight: 500;
}

.content-item span {
  flex: 1;
  color: #606266;
}

.image-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.image-list .el-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s;
}

.image-list .el-image:hover {
  transform: scale(1.05);
}

.appointment-actions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-item .el-input {
    width: 100%;
  }

  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-group > label {
    min-width: auto;
  }

  .appointment-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .content-item {
    flex-direction: column;
  }

  .content-item label {
    margin-bottom: 5px;
  }
}
</style>

